package cn.wit.summit.chwan.adapters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import java.util.List;

public class FragmentPagerAdapter extends android.support.v4.app.FragmentPagerAdapter {
    FragmentManager manager;

    public void clear() {
        if (manager == null) return;
        FragmentTransaction ft = manager.beginTransaction();
        for (int i = 0; i < getCount(); i++) {
            Fragment f = getItem(i);
            ft.detach(f);
        }
        if (getmItems() != null) {
            getmItems().clear();
            notifyDataSetChanged();
        }
    }

    public interface Provider {
        Fragment provide();
    }

    public static class Item {

        final String name;
        Provider provider;
        public Fragment fragment;

        public Item(String name, Provider provider) {
            this.name = name;
            this.provider = provider;
        }

        public Item(String name, Fragment fragment) {
            this.name = name;
            this.fragment = fragment;
        }
    }

    private List<Item> mItems;

    public FragmentPagerAdapter(FragmentManager fm) {
        super(fm);
        this.manager = fm;
    }

    public FragmentPagerAdapter(FragmentManager fm, List<Item> items) {
        super(fm);
        this.manager = fm;
        mItems = items;
    }

    public List<Item> getmItems() {
        return mItems;
    }

    public void setmItems(List<Item> mItems) {
        this.mItems = mItems;
    }

    @Override
    public Fragment getItem(int position) {
        return mItems.get(position).fragment;
    }

    @Override
    public int getCount() {
        return mItems != null
                ? mItems.size()
                : 0;
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mItems.get(position).name;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }
}
